//
//  UserRegistrationViewController.m
//  Yiqidianyin
//
//  Created by apple on 15/8/9.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "UserRegistrationViewController.h"
#import "UserRegistrationManager.h"
#import "MUser.h"
#import "MyMD5.h"
#import "CommonCrypto/CommonDigest.h"
#import "UserLondManager+Fun.h"




@interface UserRegistrationViewController ()<UITextViewDelegate>


@property (weak, nonatomic) IBOutlet UIButton *tupSeedButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneID;
@property(nonatomic,strong)UserRegistrationManager *registrationM;
@property (weak, nonatomic) IBOutlet UITextField *identifyingCode;
@property (weak, nonatomic) IBOutlet UITextField *Password;
@property (weak, nonatomic) IBOutlet UIButton *topseedIdentifyingButton;
@property(nonatomic,assign)int a;


@end

@implementation UserRegistrationViewController
{
    NSTimer * timer;
    int count;
    NSString * code1;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.topseedIdentifyingButton.layer.cornerRadius  = 8;
    self.topseedIdentifyingButton.layer.masksToBounds = YES;
    self.registrationM = [UserRegistrationManager share];
    [self.phoneID becomeFirstResponder];
    self.a = 1;
    self.Password.secureTextEntry = YES;
    
    UITapGestureRecognizer *a = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(a:)];
    [self.view addGestureRecognizer:a];
    
        // Do any additional setup after loading the view.
}

-(void)a:(UITapGestureRecognizer*)sender
{
[self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)Sendverificationcode:(id)sender
{
    
     if ([self isRightTEL:self.phoneID.text])
     {
         //发送信息
         timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(jishi) userInfo:nil repeats:YES];
         count=60;
         

         [self.registrationM RegistrationWithPhonID:self.phoneID.text BackBlock:^(id date)
          {
              NSString *str = [NSString stringWithFormat:@"%@",date[@"status"]];
             
              if ([str isEqualToString:@"0"])
              {
                 [MUser alertViewShowTitle:@"提示" andMessage:@"验证码将会发送到您的手机上，\n请注意查收" andDelegate:self controltag:1000];
              }
              else if ([str isEqualToString:@"40002"])
              {
                  [MUser alertViewShowTitle:@"提示" andMessage:@"手机号儿已被注册" andDelegate:self controltag:1000];
              }
              else
              {
                  [MUser alertViewShowTitle:@"提示" andMessage:@"验证码获取失败，请重试" andDelegate:self controltag:1000];
              }
              
          }];
     }
     else
     {
         [MUser alertViewShowTitle:@"提示" andMessage:@"请输入正确手机号" andDelegate:self controltag:2];
     }

}
- (IBAction)topRegistered:(id)sender
{
    if ([self isRightTEL:self.phoneID.text])
    {
        if (![self.Password.text isEqualToString:@""])
        {
            if (![self.identifyingCode.text isEqualToString:@""])
            {
                NSString *md5PassWord = [UserLondManager md5:self.Password.text];
                NSLog(@"%@",md5PassWord);
                
                [self.registrationM registrationWIthPhonID:self.phoneID.text andVerificationCode:self.identifyingCode.text andPassword:md5PassWord BackBlock:^(NSDictionary *dic) {
                    
                    
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    
                    [user setObject:dic[@"expiresIn"] forKey:@"expiresin"];
                    [user setObject:dic[@"userId"] forKey:@"userid"];
                    [user setObject:dic[@"userToken"] forKey:@"usertoken"];
                    
                    [user synchronize];

                    
                    NSString *str = [NSString stringWithFormat:@"%@",dic[@"status"]];
                    
                    if ([str isEqualToString:@"0"])
                    {
                        
                        [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:dic[@"userId"] password:md5PassWord completion:^(NSDictionary *loginInfo, EMError *error) {
                            if (!error)
                            {
                                UIAlertView *a = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册成功" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                                [a show];
                                
                                UIStoryboard *s = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                                UIViewController *vc = [s instantiateViewControllerWithIdentifier:@"Homepage"];
                                [self presentViewController:vc animated:YES completion:nil];

                                
                            }
                            else
                            {
                                UIAlertView *a = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登陆失败" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                                [a show];
                                NSLog(@"%@",error);
                            }
                        } onQueue:nil];
                        
                    }
                    else if ([str isEqualToString:@"40001"])
                    {
                        [MUser alertViewShowTitle:@"提示" andMessage:@"手机验证码错误" andDelegate:self controltag:1000];
                    }
                    else
                    {
                        UIAlertView *a = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册失败" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                        [a show];
                    }
                }];
            }
            else
            {
                [MUser alertViewShowTitle:@"提示" andMessage:@"请输入验证码" andDelegate:self controltag:1000];
            }
        }
        else
        {
            [MUser alertViewShowTitle:@"提示" andMessage:@"请输入密码" andDelegate:self controltag:1000];
        }
    }
    else
    {
        [MUser alertViewShowTitle:@"提示" andMessage:@"请输入正确手机号儿" andDelegate:self controltag:2];
    }
}

- (IBAction)topBackButton:(id)sender
{
    UIStoryboard *s = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    UIViewController *vc = [s instantiateViewControllerWithIdentifier:@"Enteruser"];
    [self presentViewController:vc animated:YES completion:nil];
    NSString *str = @"yes";
    [vc setValue:str forKey:@"isRun"];
}
-(BOOL)isRightTEL:(NSString *)tel
{
    if (tel.length==11) {
        return YES;
    }
    return NO;
}
-(void)jishi
{
    if (count==0)
    {
        [timer invalidate];
        self.topseedIdentifyingButton.userInteractionEnabled=YES;
        self.topseedIdentifyingButton.backgroundColor=[UIColor whiteColor];
        [self.topseedIdentifyingButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    else{
        count--;
        self.topseedIdentifyingButton.userInteractionEnabled=NO;
        self.topseedIdentifyingButton.backgroundColor=[UIColor grayColor];
        [self.topseedIdentifyingButton setTitle:[NSString stringWithFormat:@"重新获取(%d)",count] forState:UIControlStateNormal];
    }
}

- (IBAction)topEyeButton:(id)sender
{
    if (self.a == 1)
    {
        self.Password.secureTextEntry=NO;
        self.a--;
    }
    else
    {
        self.Password.secureTextEntry=YES;
        self.a++;
    }
    
}




+(NSString *)md5: (NSString *) inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    [self.view endEditing:YES];
//    
//}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
